<style lang="scss">
.select-a-date {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  >.title {
    font-size: 30px;
    color: rgba(0, 0, 0, 0.75);
    letter-spacing: 2px;
  }
  >.icon {
    font-size: 400px;
  }
}

.clock-in-details {
  background-color: #f0f0f0;
  padding: 6px;

  .points {
    height: 50vh;
    overflow-x: hidden;
    overflow-y: scroll;

    &__time-range {
      background-color: #fff;
      border-radius: 12px;
      padding: 8px;
      margin-top: 8px;
      position: relative;

      &:first-child {
        margin-top: 0;
      }

      .state-tag {
        // position: absolute;
        // top: 8px;
        // right: 8px;
        border: 1px solid;
        border-radius: 10px;
        padding: 1px 4px;
        font-size: 12px;

        &.success {
          background-color: #f6ffed;
          border-color: #b7eb8f;
          color: #389e0d;
        }
        &.await {
          background-color: #fffbe6;
          border-color: #ffe58f;
          color: #d48806;
        }
      }

      .time-range {
        font-size: 18px;
        font-weight: bold;
        color: #333;
        padding-bottom: 10px;
        border-bottom: 1px solid rgba(0, 0, 0, 0.1);
      }
    }
  }
}

.clock-in-records-container {
  .el-pagination {
    padding: 16px 0;

    .btn-prev,
    .btn-next {
      margin: 0;
      margin-right: 6px;
    }
  }

  .header-container {
    padding: 20px 0;

    &__item {
      margin-right: 10px;
    }
  }
}
</style>

<script>
import dayjs from 'dayjs'
import { clockInRecords } from '@/api/watchman'
export default {
  components: {},
  data() {
    return {
      pagination: {
        size: 10,
        current: 1,
        total: 0
      },
      filter: {
        date: null
      },
      loading: false,
      clockInRecords: [],

      idToBePreview: null,

      clockInDetailDialog: {
        visible: false
      }
    }
  },
  computed: {
    clockInRecordsFormatted() {
      return this.clockInRecords.map((record) => {
        const { id, avatar, username, phone, gender } = record
        return {
          id,
          avatar,
          name: username,
          phone,
          plan: this.planFormatter(record['class']),
          gender: this.genderFormatter(gender)
        }
      })
    },
    plan() {
      if (typeof this.idToBePreview !== 'number') return null
      console.log(this.clockInRecordsFormatted.at(this.idToBePreview).plan)
      return this.clockInRecordsFormatted.at(this.idToBePreview).plan
    }
  },
  watch: {
    'filter.date': function(date) {
      date && this.initData()
    }
  },
  methods: {
    closeDialog() {
      this.clockInDetailDialog.visible = false
    },
    planFormatter(plan) {
      const { name, time } = plan

      const timeRanges = time.map((range) => {
        const { id, start_time, end_time, dropCount, drop } = range
        return {
          id,
          beginTime: start_time,
          endTime: end_time,
          pointCount: dropCount,
          points: drop.map((item, index) => {
            return {
              id: item.id,
              name: item.name ?? `点位${index}`,
              clockInTime: this.clockInTime(item),
              state: this.stateFormatter(item),
              stateClasses: this.buildStateClasses(item),
              sequence: item.sequence
            }
          })
        }
      })

      return {
        ...plan,
        name,
        timeRanges
      }
    },
    stateFormatter(point) {
      return this.isClockIn(point) ? '已打卡' : '未打卡'
    },
    buildStateClasses(point) {
      if (this.isClockIn(point)) {
        return ['success state-tag']
      }
      return ['await state-tag']
    },
    clockInTime(point) {
      if (!this.isClockIn(point)) { return null }

      return point.dropUser.at(0).time
    },
    isClockIn(point) {
      const { dropUser } = point
      return Array.isArray(dropUser) &&
             dropUser.length > 0 &&
             dropUser.at(0).start === 2
    },
    previewClockInDetails(index) {
      this.idToBePreview = index
      console.log(index)
      this.clockInDetailDialog.visible = true
    },
    handlePageChange(currentPage) {
      this.pagination.current = currentPage
      this.refreshTable()
    },
    handlePageSizeChange(size) {
      this.pagination.size = size
      this.refreshTable()
    },
    genderFormatter(gender) {
      const m = {
        0: '女',
        1: '男'
      }
      return m[gender] ?? '未知'
    },
    async refreshTable() {
      try {
        this.loading = true
        await this.loadData()
        this.loading = false
      } catch (e) {
        this.loading = false
      }
    },
    buildParams() {
      const params = {
        date: dayjs(this.filter.date).format('YYYY-MM-DD')
      }
      return params
    },
    async fetchRecords() {
      const params = this.buildParams()

      const result = await clockInRecords(params)
      this.clockInRecords = result.data.data
      this.pagination.total = result.data.total
    },
    async loadData() {
      const result = await Promise.allSettled([this.fetchRecords()])

      const failTask = result.filter((task) => task.status === 'rejected')
      if (failTask.length <= 0) return

      throw failTask[0].reason
    },
    async initData() {
      try {
        this.loading = true
        await this.loadData()
        this.loading = false
      } catch (e) {
        this.loading = false
      }
    }
  }
}
</script>

<template>
  <div class="app-container clock-in-records-container">

    <el-card shadow="never" style="margin-bottom: 20px; border: none;">
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item label="打卡日期：" style="margin-bottom: 0">
          <el-date-picker
            v-model="filter.date"
            align="right"
            type="date"
            placeholder="选择打卡日期"
          />
        </el-form-item>
      </el-form>
    </el-card>

    <el-card shadow="never" style="border: none;height: 77vh;">
      <div v-if="!filter.date" class="select-a-date">
        <span class="title">请选择一个日期</span>
        <svg-icon icon-class="calendar" class="icon" />
      </div>
      <template v-else>
        <el-row :gutter="40">
          <el-col :span="24">
            <el-table
              v-loading="loading"
              border
              :data="clockInRecordsFormatted"
              style="width: 100%"
            >
              <el-table-column prop="id" label="序号" width="180" />
              <el-table-column label="头像" width="180">
                <template slot-scope="scope">
                  <el-image
                    style="width: 68px; height: 68px"
                    :src="scope.row.avatar"
                    fit="cover"
                    :preview-src-list="[scope.row.avatar]"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="name" label="姓名" width="180" />
              <el-table-column prop="gender" label="性别" width="180" />
              <el-table-column prop="phone" label="手机" />
              <el-table-column prop="plan.name" label="班次" />

              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="primary"
                    @click="previewClockInDetails(scope.$index)"
                  >
                    打卡详情
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>

        <el-row :gutter="40">
          <el-col :span="24">
            <el-pagination
              style="padding-bottom: 0;"
              layout="total, sizes, prev, pager, next, jumper"
              :current-page="pagination.current"
              :page-sizes="[10, 50, 100]"
              :page-size="pagination.size"
              :total="pagination.total"
              :disabled="loading"
              @size-change="handlePageSizeChange"
              @current-change="handlePageChange"
            />
          </el-col>
        </el-row>
      </template>
    </el-card>

    <el-dialog
      :close-on-click-modal="false"
      title="打卡详情"
      :visible.sync="clockInDetailDialog.visible"
      width="30%"
    >
      <div class="body clock-in-details" style="border-radius: 12px; overflow: hidden">
        <div v-if="plan" class="points">
          <div
            v-for="range in plan.timeRanges"
            :key="range.id"
            class="points__time-range"
          >
            <!-- <div class="points__time-range__state-tag success">未打卡</div> -->

            <div class="time-range">
              {{ range.beginTime }} - {{ range.endTime }}
            </div>
            <el-table :data="range.points">
              <el-table-column prop="name" label="点位名称" width="100" />
              <el-table-column prop="sequence" label="打卡顺序" width="80" />
              <el-table-column prop="clockInTime" label="打卡时间" />
              <el-table-column prop="state" label="状态">
                <template slot-scope="scope">
                  <span :class="scope.row.stateClasses">{{
                    scope.row.state
                  }}</span>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>

      <div slot="footer">
        <el-button type="primary" @click="closeDialog"> 确定 </el-button>
      </div>
    </el-dialog>
  </div>
</template>
